package com.javathread.th1.pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试pool类
 * @author Administrator
 *
 */
public class DBPoolTest {
		static DBPool pool = new DBPool(10);
		
		static CountDownLatch end;
		
		public static void main(String[] args) throws InterruptedException {
			//线程数量
			int threadCount = 50;
			end = new CountDownLatch(threadCount);
			int count = 20;//每个线程的操作次数
			AtomicInteger got = new AtomicInteger();//计数器  统计可以拿到连接的线程
			AtomicInteger notGot = new AtomicInteger();
			for (int i = 0; i < threadCount; i++) {
				Thread thread = new Thread(new Worker(count, got, notGot),"工人_"+i);
				thread.start();
			}
			end.await();//main 线程在此处等待
			System.out.println("总共尝试了: "+(threadCount * count));
			System.out.println("拿到连接的次数: " + got);
			System.out.println("没能连接的次数" + notGot);
		}
		
		static class Worker implements Runnable {
			int             count;
			AtomicInteger   got;
			AtomicInteger   notGot;
			
			public Worker(int count, AtomicInteger got, AtomicInteger notGot) {
				this.count = count;
				this.got   = got;
				this.notGot= notGot;
			}

			@Override
			public void run() {
					while (count>0) {
						try {
						Connection connection = pool.fetchConnection(3000);
						if (connection!=null) {
							try {
								connection.createStatement();
								connection.commit();
							} finally {
								pool.releaseConn(connection);
								got.incrementAndGet();
							}
						} else {
							notGot.incrementAndGet();
							System.out.println(Thread.currentThread().getName() + "等待超时!");
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} finally {
						count --;
					}
				}
				end.countDown();
			}
			
		}
}
